/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.member;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author admin
 */
@WebServlet(name = "upload", urlPatterns = {"/member/upload.do"})
public class upload extends HttpServlet {

    private static final String TMP_DIR_PATH = "D:\\temp1";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "../images/data/avatar";
    private File destinationDir;

    @Override
    public void init() throws ServletException {
        //Khỏi tạo upload:
        tmpDir = new File(TMP_DIR_PATH);

        //Nếu chưa tồn tại thì tạo mới:
        if (tmpDir.exists() == false) {
            tmpDir.mkdir();
        }

        String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        destinationDir = new File(realPath);
    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        try {
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

            fileItemFactory.setSizeThreshold(1 * 1024 * 1024);
            fileItemFactory.setRepository(tmpDir);

            ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
            try {
                // Parse the request          
                
                List items = uploadHandler.parseRequest(request);
                Iterator itr = items.iterator();

                ArrayList<String> listFile = new ArrayList<String>();

                while (itr.hasNext()) {
                    FileItem item = (FileItem) itr.next();

                    //Handle Form Fields                    
                    if (item.isFormField()) {
                        //Xử lý field ....
                    } else {
                        //Handle Uploaded files
                        //Write data to file  
                        String content = item.getContentType();
                        if (content.contains("png") || content.contains("jpg") || content.contains("gif") || content.contains("jpeg")) {
                            File file = new File(destinationDir, item.getName());
                            listFile.add(file.getName());
                            item.write(file);
                        }
                    }
                }
                session.setAttribute("upload", listFile);
                

            } catch (FileUploadException ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Lỗi phân tích yêu cầu upload file !", ex);
                session.setAttribute("error", 1);
            } catch (Exception ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Lỗi upload file !", ex);
                session.setAttribute("error", 1);
            }
        }finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
